package ferramentas;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Seguranca {

    public static String converteParaMD5(final String text) {
        try {
            // Create a Message Digest from a Factory method
            MessageDigest message_digest = MessageDigest.getInstance("MD5");
            // Create the message
            byte[] message = text.getBytes();
            // Update the message digest with some more bytes
            // This can be performed multiple times before creating the hash
            message_digest.update(message);
            // Create the digest from the message
            byte[] another_message_digest = message_digest.digest();
            String hash = "";
            for (byte message_digest_byte : another_message_digest) {
                hash += byteToHex(message_digest_byte);
            }
            // Return
            return hash;
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Seguranca.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    private static String byteToHex(byte data) {
        StringBuffer buf = new StringBuffer();
        buf.append(toHexChar((data >>> 4) & 0x0F));
        buf.append(toHexChar(data & 0x0F));
        return buf.toString();
    }

    private static char toHexChar(int i) {
        if ((0 <= i) && (i <= 9)) {
            return (char) ('0' + i);
        } else {
            return (char) ('a' + (i - 10));
        }
    }
}
